import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/api/user'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const router = useRouter()

  // 从路由配置中计算菜单列表
  const menuList = computed(() => {
    const rootRoute = router.options.routes.find(route => route.path === '/')
    if (rootRoute && rootRoute.children) {
      return rootRoute.children.filter(route => !route.meta?.hidden)
    }
    return []
  })

  // 登录
  const userLogin = async (loginData) => {
    try {
      // 模拟登录API调用
      const response = await login(loginData)
      if(response.code === 200) {
        token.value = response.data.AccessToken
        localStorage.setItem('token', response.data.AccessToken)
        return Promise.resolve(response.data)
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      return Promise.reject(error)
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    // 跳转到登录页
    window.location.href = '/login'
  }

  return {
    token,
    userInfo,
    menuList, // 计算属性，从路由配置中获取
    userLogin,
    logout
  }
})